﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common
{
    /// <summary>
    /// 分片器构造
    /// </summary>
    public class Slicer
    {
        /// <summary>
        /// 创建一个新的分片器
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="array">集合数据</param>
        /// <param name="pageSize">每页大小</param>
        /// <returns></returns>
        public static Slicer<T> New<T>(IEnumerable<T> array, int pageSize)
        {
            Slicer<T> slicer = new Slicer<T>(array, pageSize);
            return slicer;
        }
    }
    /// <summary>
    /// 分片器
    /// </summary>
    public class Slicer<T>
    {
        /// <summary>
        /// 分片器
        /// </summary>
        /// <param name="array"></param>
        /// <param name="pageSize"></param>
        public Slicer(IEnumerable<T> array, int pageSize)
        {
            Array = array;
            PageSize = pageSize;
        }

        /// <summary>
        /// 单片大小
        /// </summary>
        private int PageSize { get; set; }

        /// <summary>
        /// 需要分片的集合
        /// </summary>
        private IEnumerable<T> Array { get; set; }

        /// <summary>
        /// 当前索引
        /// </summary>
        private int CurrentCount { get; set; }

        /// <summary>
        /// 当前分块
        /// </summary>
        private IEnumerable<T> CurrentArray { get; set; }
        /// <summary>
        /// 判断是否还有剩余的分配
        /// </summary>
        /// <returns></returns>
        public bool Next()
        {
            int count = Array.Count();
            if (CurrentCount >= count)
            {
                return false;
            }
            CurrentArray = Array.Skip(CurrentCount).Take(PageSize);
            CurrentCount = CurrentCount + CurrentArray.Count();
            return true;
        }

        /// <summary>
        /// 重置索引
        /// </summary>
        public void Reset()
        {
            CurrentCount = 0;
        }

        /// <summary>
        /// 拿去下一个分配集合
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> Take()
        {
            return CurrentArray;
        }

        /// <summary>
        /// 拿到一个List集合类型
        /// </summary>
        /// <returns></returns>
        public List<T> TakeList()
        {
            return CurrentArray.ToList();
        }
    }
}
